%--------------------------------------------------------------------------
% computes the eigenvalues using the characteristic equation that is
% obtained from the adjoint eigenvalue problem
%--------------------------------------------------------------------------


function X = lo_comp_eigs_adj(k, M, lambda0)

if nargin == 2
    lambda0 = [0; 0];
end

opts = optimset('tolfun',1e-10);
X = fsolve(@(x) fun(x, k, M), [lambda0(1); lambda0(2)], opts);

fprintf('lambda = %.4e + 1i * %.4e (|F| = %.4e)\n', X(1), X(2), norm(fun(X, k, M)));

% lambda = linspace(0, 250, 100);
% for i = 1:length(lambda)
%    
%     tmp = fun([lambda(i), 0], k, M);
%     plot(lambda(i), tmp(1), 'k*');
%     hold on;
%     
% end

function F = fun(X, k, M)

lambda = X(1) + 1i * X(2);

mu = sqrt(-k^2 - lambda);

if k > 1e-10
    w = @(z)  -(((-z + 1) * sinh(k) + z * cosh(k) * k) .* sinh(k * z) - k * sinh(k) * z .* cosh(k * z)) * M * k / (-0.2e1 * cosh(k) * sinh(k) + 0.2e1 * k);
else
    w = @(z) -k ^ 2 * (z - 1) .* M .* (0.280e3 + ((z .^ 4) - 0.4e1 / 0.3e1 * z - 0.4e1 / 0.3e1 * (z .^ 3) + 0.10e2 / 0.3e1 * (z .^ 2) + 0.1e1) * k ^ 4 + (-0.56e2 / 0.3e1 * z + 0.28e2 + (28 * z .^ 2)) * k ^ 2) .* (z .^ 2) / 0.1120e4;
end

% the problem in general
tmp = mu * sin(mu)  + ...
    + quadgk(@(z) w(z) .* z .* cos(mu*z), 0, 1);


F(1) = real(tmp);
F(2) = imag(tmp);